﻿using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Eflong.Utility
{
    /// <summary>
    ///系统时间类
    /// </summary>
    [StructLayout( LayoutKind.Sequential )]
    public class SystemTime
    {
        public ushort year;
        public ushort month;
        public ushort dayofweek;
        public ushort day;
        public ushort hour;
        public ushort minute;
        public ushort second;
        public ushort milliseconds;
    }

    public class WinAPI
    {
        [DllImport( "Kernel32.dll" )]
        private static extern bool SetSystemTime( [In , Out] SystemTime st );

        /**/

        /// <summary>
        /// 设置系统时间
        /// </summary>
        /// <param name="newdatetime">新时间</param>
        /// <returns></returns>
        public static bool SetSysTime( DateTime newdatetime )
        {
            SystemTime st = new SystemTime( );
            st.year = Convert.ToUInt16( newdatetime.Year );
            st.month = Convert.ToUInt16( newdatetime.Month );

            int hourTimeZone = TimeZone.CurrentTimeZone.GetUtcOffset( new DateTime( 2001 , 09 , 01 ) ).Hours;

            //处置北京时间
            int nBeijingHour = newdatetime.Hour - hourTimeZone;// 8;
            if ( nBeijingHour < 0 )
            {
                nBeijingHour += 24;
                st.day = Convert.ToUInt16( newdatetime.Day - 1 );
                if ( newdatetime.DayOfWeek == DayOfWeek.Sunday )
                {
                    st.dayofweek = Convert.ToUInt16( DayOfWeek.Saturday );
                }
                else
                {
                    st.dayofweek = Convert.ToUInt16( newdatetime.DayOfWeek - 1 );
                }
            }
            else
            {
                st.day = Convert.ToUInt16( newdatetime.Day );
                st.dayofweek = Convert.ToUInt16( newdatetime.DayOfWeek );
            }

            st.hour = Convert.ToUInt16( nBeijingHour );
            st.minute = Convert.ToUInt16( newdatetime.Minute );
            st.second = Convert.ToUInt16( newdatetime.Second );
            st.milliseconds = Convert.ToUInt16( newdatetime.Millisecond );
            return SetSystemTime( st );
        }

        //以下为方法二调用API代码
        public const int WS_HIDE = 0;//窗口隐藏

        public const int WS_SHOWNORMAL = 1;//窗口处于正常状态

        public const int WS_SHOWMIN = 2;//窗口处于最小化状态

        public const int WS_SHOWMAX = 3;//窗口处于最大化状态

        /// <summary>
        /// 显示窗口
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <param name="cmdShow">显示模式</param>
        /// <returns></returns>

        [System.Runtime.InteropServices.DllImport( "User32.dll" )]
        public static extern bool ShowWindowAsync( IntPtr hWnd , int cmdShow );

        [System.Runtime.InteropServices.DllImport( "User32.dll" )]
        public static extern bool SetForegroundWindow( IntPtr hWnd );

        [System.Runtime.InteropServices.DllImport( "User32.dll" )]
        public static extern IntPtr SetActiveWindow( IntPtr hWnd );

        /// <summary>
        /// 查找窗口的句柄

        /// </summary>
        /// <param name="className">指向包含了窗口类名的空中止（C语言）字串的指针；或设为零，表示接收任何类</param>
        /// <param name="titleName">指向包含了窗口文本（或标签）的空中止（C语言）字串的指针；或设为零，表示接收任何窗口标题</param>
        /// <returns>句柄</returns>
        [System.Runtime.InteropServices.DllImport( "User32.dll" , EntryPoint = "FindWindow" )]
        public static extern int FindWindow( string className , string titleName );
    }

    //

    /// <summary>
    /// 注：API函数GetForegroundWindow用来获得前台窗口的句柄，
    /// // 这里的“前台窗口”是指前台应用程序的活动窗口
    /// //类ForegroundWindow继承了框架提供的IWin32Window接口，

    /// 并定义了一个静态的IWin32Window属性Instance，用来获得前台窗口的句柄。

    ///
    /// openfile.ShowDialog(ForegroundWindow.Instance);
    /// </summary>
    ///

    public class ForegroundWindow : IWin32Window
    {
        private static ForegroundWindow _window = new ForegroundWindow( );

        private ForegroundWindow( ) { }

        public static IWin32Window Instance
        {
            get { return _window; }
        }

        [DllImport( "user32.dll" )]
        private static extern IntPtr GetForegroundWindow( );

        IntPtr IWin32Window.Handle
        {
            get
            {
                return GetForegroundWindow( );
            }
        }
    }

    public class WinSound
    {
        [DllImport( "winmm.dll" , EntryPoint = "mciSendString" , CharSet = CharSet.Auto )]
        public static extern int mciSendString(
         string lpstrCommand ,
         string lpstrReturnString ,
         int uReturnLength ,
         int hwndCallback
        );

        [System.Runtime.InteropServices.DllImport( "winmm.DLL" , EntryPoint = "PlaySound" , SetLastError = true )]
        public static extern bool PlaySound( string szSound , System.IntPtr hMod , PlaySoundFlags flags );

        // 表示当前机器上波形输出设备个数

        [DllImport( "Winmm.dll" , CharSet = CharSet.Auto )]
        public static extern int waveOutGetNumDevs( );

        // 表示当前机器上MIDI输出设备个数
        [DllImport( "Winmm.dll" , CharSet = CharSet.Auto )]
        public static extern int midiOutGetNumDevs( );

        private string _sname;

        public bool bSounding = false;

        public bool Enabled { get; set; }

        public string sFileName
        {
            get { return _sname; }
            set
            {
                _sname = value;
                if ( !File.Exists( _sname ) )
                {
                    throw new Exception( "报警声音文件不存在" );
                }
            }
        }

        public void PlaySound( )
        {
            if ( File.Exists( sFileName ) )
            {
                if ( !bSounding )
                {
                    bSounding = true;
                    PlaySound( sFileName );
                    bSounding = false;
                }
            }
            else
            {
            }
        }

        private BackgroundWorker worker;

        public void PlaySound( string sFileName )
        {
            worker = new BackgroundWorker( );
            worker.DoWork += new DoWorkEventHandler( worker_DoWork );
            worker.RunWorkerAsync( sFileName );
        }

        private void worker_DoWork( object sender , DoWorkEventArgs e )
        {
            if ( Enabled )
            {
                string sFileName = e.Argument.ToString( );
                WinSound.PlaySound( sFileName , new System.IntPtr( ) , WinSound.PlaySoundFlags.SND_SYNC );
            }
        }

        [System.Flags]
        public enum PlaySoundFlags : int
        {
            SND_SYNC = 0x0000 ,
            SND_ASYNC = 0x0001 ,
            SND_NODEFAULT = 0x0002 ,
            SND_LOOP = 0x0008 ,
            SND_NOSTOP = 0x0010 ,
            SND_NOWAIT = 0x00002000 ,
            SND_FILENAME = 0x00020000 ,
            SND_RESOURCE = 0x00040004
        }
    }
}